package controllers;

import models.Answer;
import models.Question;
import models.QuestionStatistics;
import play.modules.router.Any;
import play.mvc.Controller;

import java.util.List;


public class Application extends Controller {

    @Any("/q")
    public static void q(int count) {
//        QuestionsSevice questionsSevice = Spring.getBeanOfType(QuestionsSevice.class);
//        questionsSevice.getList();

        Question question = Question.find("from models.Question where status = 1 order by browseCount  ").first();
        question.browseCount = question.browseCount == null ? 1 : question.browseCount + 1;
        question.save();

        List<Answer> answers = Answer.find("from models.Answer where questionId = " + question.id).fetch();

        renderArgs.put("question", question);
        renderArgs.put("answers", answers);
        renderArgs.put("count", count);

        render("/q.html");
    }

    @Any("/a")
    public static void a(long questionId, Long answerId, int count) {
        Question question = Question.findById(questionId);
        if (question != null && answerId != null) {

            QuestionStatistics questionStatistics = new QuestionStatistics();
            questionStatistics.setQuestionId(questionId);
            questionStatistics.setAnswerId(answerId);

            if (answerId == 0) {
                question.missCount = question.missCount == null ? 1 : question.missCount + 1;
                questionStatistics.setStatus(0);
            } else if (question.answerId.longValue() == answerId.longValue()) {
                question.trueCount = question.trueCount == null ? 1 : question.trueCount + 1;
                questionStatistics.setStatus(1);
            } else {
                question.falseCount = question.falseCount == null ? 1 : question.falseCount + 1;
                questionStatistics.setStatus(2);
            }

            question.responseCount = question.responseCount == null ? 1 : question.responseCount + 1;
            question.save();

            questionStatistics.save();


        }
        redirect("/q?count=" + count);
    }


}